package com.yfbao.horizon.schedule.tk.service;

import com.yfbao.horizon.schedule.tk.annotation.CompositeCacheable;
import com.yfbao.horizon.schedule.tk.dto.UserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@CacheConfig(cacheNames="user")
public class TestService {

    @Autowired
    private CacheManager cacheManager;

    @CompositeCacheable(cacheNames="userCom1",key="#id")
    public UserDto getUserById(Long id){
        log.info("CompositeCache user:"+id);
        return newUser(id);
    }

    @Cacheable(cacheNames = "user")
    public UserDto getUserById2(Long id){
        log.info("cacheable user:"+id);
        return newUser(id);
    }


    @Cacheable(cacheNames = {"usermutil","tt"})
    public UserDto getUserByIdMutil(Long id){
        log.info("cacheable user:"+id);
        return newUser(id);
    }

    @Cacheable
    public UserDto getCacheUserById(Long id){
        log.info("cacheable no key user:"+id);
        return newUser(id);
    }

    @Cacheable(key="#user.id")
    public UserDto getCacheUser(UserDto user){
        log.info("cacheable no key user:"+user.getId());
        return newUser(user.getId());
    }

    @Cacheable
    public UserDto getCacheUserByIdAAA(Long id,String aaa){
        log.info("cacheable no key user:"+id+", a:"+aaa);
        return newUser(id);
    }

    @Cacheable
    public UserDto getCacheUserByIdCCC(Long id,String aaa,UserDto bean){
        log.info("cacheable no key user:"+id+", a:"+aaa);
        return newUser(id);
    }

    @Cacheable
    public UserDto getCacheUserByIdBBB(String aaa){
        log.info("cacheable no key user:"+", a:"+aaa);
        return null;
    }



    @CacheEvict
    public void update(Long id){
        log.info("update user:"+id);
    }

    public void updateNoAnnotaion(Long id){
        log.info("update cacheManager user:"+id);
        Cache user = cacheManager.getCache("user");
        user.evict(id);
    }



    private UserDto newUser(Long id){
        UserDto userDto = new UserDto();
        userDto.setId(id);
        userDto.setName(id.toString());
        return userDto;
    }
}
